﻿using Lamex.Base;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Lamex.SIESystemManager.Calculate
{
    public class C_Routing_Group
    {
        //获取流水号
        public int[] GetNumber(string Calculate_Desc)
        {
            int[] result = { 0, 0 };

            string sql = @" select Routing_Group,Calculate FROM [LamexMESManager].[dbo].[B_IE_Calculator_Routing]
                             where Calculate_Desc='" + Calculate_Desc + "'";
            string sqlMaxNumber = @" select top 1 Calculate,Routing_Group FROM [LamexMESManager].[dbo].[B_IE_Calculator_Routing] order by IDNO DESC";
            DataTable dt = BaseBuildSql.GetDataTableBySql(sql);//组别代码
            DataTable dtNumber = BaseBuildSql.GetDataTableBySql(sqlMaxNumber);//流水号2-99
            //如果计数器存在，则不增加记录，取存在的值
            if (dt.Rows.Count > 0)
            {
                result[0] = Convert.ToInt32(dt.Rows[0]["Routing_Group"]);//组
                result[1] = Convert.ToInt32(dt.Rows[0]["Calculate"]);//计数器流水号

            }
            else
            {
                //数据库大于1笔数据时生成流水号和组号
                if (dtNumber.Rows.Count > 0)
                {
                    if (Convert.ToInt32(dtNumber.Rows[0]["Calculate"]) >= 2 && Convert.ToInt32(dtNumber.Rows[0]["Calculate"]) < 99)
                    {
                        result[0] = Convert.ToInt32(dtNumber.Rows[0]["Routing_Group"]);//取表里的组号
                        result[1] = Convert.ToInt32(dtNumber.Rows[0]["Calculate"]) + 1;//流水号+1

                    }
                    else if (Convert.ToInt32(dtNumber.Rows[0]["Calculate"]) == 99)
                    {
                        result[0] = Convert.ToInt32(dtNumber.Rows[0]["Routing_Group"]) + 1;//组号+1
                        result[1] = 2;//流水号重新开始算-最小值为2

                    }
                }
                //第一笔数据取默认值
                else
                {
                    result[0] = 44000001;//默认最小值
                    result[1] = 2;//默认最小值
                }

                string insert = @"insert into [LamexMESManager].[dbo].[B_IE_Calculator_Routing]([Routing_Group],[Calculate],[Calculate_Desc],[Date_TS])
                                                  values(" + result[0] + "," + result[1] + ",'" + Calculate_Desc + "', getdate())";
                BaseBuildSql.ExecuteNonQuery(insert);
            }

            return result;

        }

        public DataTable GetTable_Routing()
        {
            DataTable dt = new DataTable();
            dt.Columns.AddRange(new DataColumn[] {   
         new DataColumn("Serial",typeof(int)),  
         new DataColumn("Routing_Group",typeof(int)),  
         new DataColumn("Calculate",typeof(int)),  
         new DataColumn("Calculate_Desc",typeof(string)), 
         new DataColumn("Date_TS",typeof(DateTime)),
         new DataColumn("Update_User",typeof(string))});
            return dt;
        }

    }
}
